package com.jiajia.study.chapter01.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author zjiajia
 * @date 2024/7/4 12:30
 */
@Slf4j
public class TestByteBuffer {
    public static void main(String[] args) {
        String src = "D:\\IDEAWorkPlace\\sl-express\\netty_study2024\\itheima_netty\\src\\main\\resources\\1.txt";
        FileChannel channel = null;
        try {
            log.info("系统核心数是：{}",Runtime.getRuntime().availableProcessors());
            channel = new FileInputStream(src).getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(10);
            while(true){
                int length = channel.read(byteBuffer);
                log.info("读取到的字节数是：{}",length);
                if(-1 == length){
                    break;
                }
                // 切换之读模式
                byteBuffer.flip();
                while(byteBuffer.hasRemaining()){

                    byte b = byteBuffer.get();
                    log.info("读取到的字节是：{}",(char)b);
                }
                // 切换成写模式
                byteBuffer.clear();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(channel != null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
